#include <stdio.h>
#include "ohos_init.h"
#include "ohos_types.h"

#include <hi_types_base.h>
#include <hi_early_debug.h>
#include <hi_task.h>
#include <hi_uart.h>
#include "../MQTTServer/mqtt_connect.h"
#include "i_led.h"

#define WRITE_BY_INT
#define UART_DEMO_TASK_STAK_SIZE 2048
#define UART_DEMO_TASK_PRIORITY  25
#define DEMO_UART_NUM            HI_UART_IDX_1
#define UART_BUFF_SIZE           32

hi_u32 g_uart_demo_task_id = 0;

char *FIRE = "fire";
char *NOFIRE = "nofire";

extern int g_off_time;;

static hi_void *uart_demo_task(hi_void *param)
{
    hi_u8 uart_buff[UART_BUFF_SIZE] = {0};
    hi_u8 *uart_buff_ptr = uart_buff;
    hi_unref_param(param);
    printf("i uart successfully ! ! !\n");

    for (;;) {
        hi_s32 len = hi_uart_read(DEMO_UART_NUM, uart_buff_ptr, UART_BUFF_SIZE);
        if (len > 0) {
#ifdef WRITE_BY_INT
            if (len == 5 && uart_buff_ptr[0] == 0x55 && uart_buff_ptr[1] == 0xAA && uart_buff_ptr[3] == 0 && uart_buff_ptr[4] == 0) {
                if (uart_buff_ptr[2] == 0x00) {
                    led_off();
                    i_mqtt_send(NOFIRE);
                } else if (uart_buff_ptr[2] == 0x01) {
                    led_on();
                    g_off_time = 2;                         // 2s 后自动关闭
                    i_mqtt_send(FIRE);
                }
            } else {
                printf("recv(%d): ", len);
                for (int i = 0; i < len && i < UART_BUFF_SIZE; i++) {
                    putchar(uart_buff_ptr[i]);
                }
                printf("\n");
            }
            // hi_uart_write(DEMO_UART_NUM, uart_buff_ptr, len);
#else
            hi_uart_write_immediately(DEMO_UART_NUM, uart_buff_ptr, len);
#endif
        } else {
            printf("Read nothing!\n");
            hi_sleep(1000); /* sleep 1000ms */
        }
    }

    hi_task_delete(g_uart_demo_task_id);
    g_uart_demo_task_id = 0;

    return HI_NULL;
}

/*
 * This demo simply shows how to read datas from UART2 port and then echo back.
 */
hi_void uart_demo(hi_void)
{
    hi_u32 ret;
    hi_uart_attribute uart_attr = {
        .baud_rate = 115200, /* baud_rate: 115200 */
        .data_bits = 8,      /* data_bits: 8bits */
        .stop_bits = 1,
        .parity = 0,
    };

    /* Initialize uart driver */
    ret = hi_uart_init(DEMO_UART_NUM, &uart_attr, HI_NULL);
    if (ret != HI_ERR_SUCCESS) {
        printf("Failed to init uart! Err code = %d\n", ret);
        return;
    }

    /* Create a task to handle uart communication */
    hi_task_attr attr = {0};
    attr.stack_size = UART_DEMO_TASK_STAK_SIZE;
    attr.task_prio = UART_DEMO_TASK_PRIORITY;
    attr.task_name = (hi_char*)"uart_demo";
    ret = hi_task_create(&g_uart_demo_task_id, &attr, uart_demo_task, HI_NULL);
    if (ret != HI_ERR_SUCCESS) {
        printf("Falied to create uart demo task!\n");
    }
}

SYS_RUN(uart_demo);
